"""
S4 Custom Prompts Replace Node  
Author: S4MUEL
GitHub: https://github.com/S4MUEL-404/ComfyUI-S4API

Replace or remove text in prompts with advanced pattern matching.
"""

import re
from ..s4_logger import S4APILogger, log_processing_step


class S4PromptsReplace:
    """
    Replace or remove text in input prompts with flexible matching options.
    """

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "text": (
                    "STRING", 
                    {
                        "forceInput": True,
                        "tooltip": "Input text to process"
                    }
                ),
                "original_text": (
                    "STRING", 
                    {
                        "default": "", 
                        "multiline": True,
                        "tooltip": "Text to find and replace"
                    }
                ),
                "replacement_text": (
                    "STRING", 
                    {
                        "default": "", 
                        "multiline": True,
                        "tooltip": "Replacement text (empty to remove)"
                    }
                ),
            },
            "optional": {
                "case_sensitive": (
                    "BOOLEAN",
                    {
                        "default": True,
                        "tooltip": "Whether the search should be case sensitive"
                    }
                ),
                "use_regex": (
                    "BOOLEAN",
                    {
                        "default": False,
                        "tooltip": "Use regular expressions for pattern matching"
                    }
                ),
                "replace_all": (
                    "BOOLEAN",
                    {
                        "default": True,
                        "tooltip": "Replace all occurrences (vs. only first occurrence)"
                    }
                ),
            }
        }

    RETURN_TYPES = ("STRING",)
    RETURN_NAMES = ("processed_text",)
    FUNCTION = "replace_text"
    CATEGORY = "💀PromptsO"
    DESCRIPTION = "Replace or remove text in prompts with advanced pattern matching options."

    @classmethod
    def IS_INPUT_INTERFACE(cls, input_name):
        return input_name in ["text"]

    def validate_inputs(self, text: str, original_text: str) -> None:
        """Validate input parameters"""
        if not text:
            raise ValueError("Input text cannot be empty")
        if not original_text.strip():
            raise ValueError("Original text to replace cannot be empty")

    def replace_text(self, text, original_text, replacement_text="", 
                    case_sensitive=True, use_regex=False, replace_all=True):
        """Replace text based on specified parameters"""
        
        self.validate_inputs(text, original_text)
        
        log_processing_step("PromptsReplace", "Starting text replacement")
        
        S4APILogger.debug("PromptsReplace", f"Input length: {len(text)} chars")
        original_preview = original_text[:30] + "..." if len(original_text) > 30 else original_text
        S4APILogger.debug("PromptsReplace", f"Search pattern: {original_preview}")
        
        if replacement_text:
            replacement_preview = replacement_text[:30] + "..." if len(replacement_text) > 30 else replacement_text
            S4APILogger.debug("PromptsReplace", f"Replacement: {replacement_preview}")
        else:
            S4APILogger.debug("PromptsReplace", "Operation: Remove text")
        
        S4APILogger.debug("PromptsReplace", f"Options: Case-sensitive={case_sensitive}, Regex={use_regex}, Replace-all={replace_all}")

        try:
            if use_regex:
                # Regular expression replacement
                flags = 0 if case_sensitive else re.IGNORECASE
                count = 0 if replace_all else 1
                
                result = re.sub(original_text, replacement_text, text, count=count, flags=flags)
                
                # Count actual replacements made
                test_matches = re.findall(original_text, text, flags=flags)
                matches_found = len(test_matches)
                
            else:
                # Simple string replacement
                if not case_sensitive:
                    # Case insensitive replacement using regex
                    flags = re.IGNORECASE
                    escaped_original = re.escape(original_text)
                    count = 0 if replace_all else 1
                    result = re.sub(escaped_original, replacement_text, text, count=count, flags=flags)
                    
                    # Count matches
                    test_matches = re.findall(escaped_original, text, flags=flags)
                    matches_found = len(test_matches)
                else:
                    # Simple case-sensitive replacement
                    if replace_all:
                        matches_found = text.count(original_text)
                        result = text.replace(original_text, replacement_text)
                    else:
                        matches_found = 1 if original_text in text else 0
                        result = text.replace(original_text, replacement_text, 1)

            changes_made = len(text) - len(result) if replacement_text == "" else matches_found

            # Log results
            result_info = f"Matches: {matches_found}, Changes: {changes_made}"
            result_info += f", Length: {len(text)} → {len(result)} chars"
            
            if result != text:
                preview = result[:50] + "..." if len(result) > 50 else result
                result_info += f", Preview: {preview}"
                S4APILogger.success("PromptsReplace", f"Text replacement completed - {result_info}")
            else:
                S4APILogger.info("PromptsReplace", f"No changes made - {result_info}")

            return (result,)

        except re.error as e:
            error_msg = f"Regular expression error: {str(e)}"
            S4APILogger.error("PromptsReplace", error_msg)
            raise ValueError(error_msg)
        
        except Exception as e:
            error_msg = f"Text replacement error: {str(e)}"
            S4APILogger.error("PromptsReplace", error_msg)
            raise ValueError(error_msg)
